package com.example.composableexample.stateflow

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlin.random.Random

/**
 * author: LiLiang
 * createTime: 2022/10/7-10:24
 * remark:
 **/
class StateFlowViewModel(
    private val savedStateHandle: SavedStateHandle
) : ViewModel() {

    val color = savedStateHandle.getStateFlow("color", 0xFFFFFFFF)

    var composeColor by mutableStateOf(savedStateHandle["color"] ?: 0xFFFFFFFF)
        private set

    fun generateNewColor() {
        val color = Random.nextLong(0xFFFFFFFF)
        savedStateHandle["color"] = color
        composeColor = color
    }
}